<?php
/**
 * generate query SELECT, INSERT, UPDATE, DELETE
 * @param FOR INSERT, UPDATE
 * $param_qry = array(
		'table' => 'gain_wip',
		'cols' => array(
			'id_invoice','','NULL',
			'invoice_no','','NULL',
			'date_bill','','NULL',
			'updated','','NOW()',
			'date_bill','%d',$_SESSION[SESSION_L],
		),
		'where' => SQL('id_invoice=%d',$id)
	);
 *	echo db_query($param_qry);
 *	$db->Execute(db_query($param_qry));
 * @return unknown_type
 */
function db_query($param, $exe = 1, $type = ''){
	global $db;
	$array_fixed = array('%d', '%f', '%s');

	//check param and return text err
	$upd = 0;
	if (isset($param['where'])) {
		$upd = 1;
		$sql = 'UPDATE {table} SET {column_values} WHERE {where}';
	} else {
		$sql = 'INSERT INTO {table}({column}) VALUES({values})';
	}

	$cols_list = array_chunk($param['cols'], 3);
	foreach ($cols_list as $k => $v) {
		$cnt_v = count($v);
		if ($cnt_v == 3) {
			$v[0] = trim($v[0]);
			$v[1] = trim($v[1]);
			$v[2] = trim($v[2]);
			$column_list[] = $v[0];

			if (in_array($v[1], $array_fixed) || $v[1] == '') {
				if ($v[1] == '') {
					$values_list[] = $v[2];
					$column_value_list[] = $v[0].'='.$v[2];
				} else {
					$values_list[] = SQL($v[1], $v[2]);
					$column_value_list[] = SQL($v[0].'='.$v[1], $v[2]);
				}
			} else {
				$ax = '|'.$v[0].'|'.$v[1].'|'.$v[2].'|';
				//return 'param meter error!!!';//TODO beem: add to table and read it!
			}
		} else {
			$ax = '|'.$v[0].'|'.$v[1].'|'.$v[2].'|';
		}
	}
	$column = implode(', ', $column_list);
	$values = implode(', ', $values_list);
	$column_values = implode(', ', $column_value_list);

	//return sql query
	$main_list = array('{table}', '{column}', '{values}', '{column_values}', '{where}');
	$main_value = array($param['table'], $column, $values, $column_values, $param['where']);
	$sql = str_replace($main_list, $main_value, $sql);


	if ($ax) {
		echo 'Param meter error!!!>>> |'.$ax.'|'.$sql;
	}

	if ($exe == 1) {
		$r = $db->Execute($sql, $type);
		if ($upd) {
			return $r;
		} else {
			return $db->Insert_ID();
		}
	} else if ($exe == 'return') {
		return $sql;
	} else {
		echo $sql;
	}
}

/**
 *
 * @param $text
 * @param $type error|info
 * @param $more_attr array('style' => 'width: 600px', 'id' => 'notify_user', 'class' => 'notify_class');
 * @return unknown_type
 */
function fw_notify_msg($text, $type = 'info', $more_attr = array()) {
	$notify_style = 'padding: 0.7em; ';
	if ($more_attr['style'] != '') {
		$notify_style = $more_attr['style'];
	}
	$br_class = '';
	if ($more_attr['id'] != '' || $more_attr['class'] != '') {
		if ($more_attr['id'] != '') {
			$notify_id = ' id="'.$more_attr['id'].'"';
			$notify_id_use = $more_attr['id'];
		}
		if ($more_attr['class'] != '') {
			$notify_id = ' id="'.$more_attr['class'].'"';
			$notify_id_use = $more_attr['class'];
		}

		$br_class = 'class="'. $more_attr['id'].' '.$more_attr['class'].'"';
		$br_class = '<br '. $br_class .' class="clr" />';
		$id = $more_attr['id'];
	} else {
		$notify_id = ' id="fw_notify_msg"';
		$notify_id_use = 'fw_notify_msg';
		$id = $notify_id_use;
	}
	if ($more_attr['un_msg_func'] != 1) {
		$text = msg($text);
	}

	//add remove icon
	$close_icon = '';
	if ($more_attr['close_element'] > -1) {
		$close_icon = '<span class="ui-icon ui-icon-close fw-point" style="float: right; margin-top: -8px; margin-right: -5px;" onclick="$(\'div[id^='.$id.']\').remove();" title="'.msg('close').'"></span>';
	}

	if ($type == 'error') {
		$notify_icon = 'ui-state-error';
		$icon_show = ' ui-icon-alert';
	} else if ($type == 'info') {
		$notify_icon = 'ui-state-highlight';
		$icon_show = ' ui-icon-info';
	} else if ($type == 'notify') {
		$notify_icon = 'ui-state-default';
		$icon_show = ' ui-icon-info';
	}

	if ($more_attr['close_element'] > 0) {
		$script = '
		<script type="text/javascript">
			setTimeout("$(\'div[id^='.$id.']\').remove()", (parseFloat('.$more_attr['close_element'].'*1)*1000));
		</script>
		';
	}
	return '
	<div'.$notify_id.' class="'.$notify_icon.' ui-corner-all" style="margin-bottom: 5px;'.$notify_style.'">
		<p><span class="ui-icon'.$icon_show.'" style="float: left; margin-right: 0.3em;"></span>'.$close_icon.$text.'</p>
	</div>'.$script;
}

/**
 * get microtime timestamp
 *
 * @return microtime seconds
 */
function getts(){
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}

/**
 * translate
 * @param string $s
 * @param string $format
 * @return string with translation
 */
function msg($s, $format=''){
	global $lng, $db;
	if (trim($s) == '') {
		return;
	}

	$s = strtolower($s);
	if (isset($lng[$s])) {
		return $lng[$s];
	} else {
		if(preg_match('!\+|\"|\\\'!', $s)){
			return $s;
		}
		if (trim($s) != '') {
		  	$sql = SQL('SELECT word_key
		  	FROM gain_lang_word
		  	WHERE word_key=%s', $s);
		  	$t = $db->GetOne($sql, 'fw');

		  	if (!$t) {
		  		$t = str_replace('_', ' ', $s);
		  		$sql = SQL('INSERT INTO gain_lang_word(word_key,id_word_group) VALUES(%s,0)', $s);
		  		$db->Execute($sql,'fw');
		  		$sql = SQL('INSERT INTO gain_lang_translation(id_lang,word_key,translation,updated,updated_by) VALUES(1,%s,%s,NOW(),%d)', $s, $t, $_SESSION[SESSION_L]);
		  		$db->Execute($sql,'fw');
	  		}//else should recache
	  		return $t;
		}
	}
}


//cleanup functions
$arrArguments = array();
$intArgumentIndex = 0;
function parseArgument($arrMatches){
	global $arrArguments, $intArgumentIndex;
	$strMatch = $arrMatches[0];
	$strArgument = @$arrArguments[$intArgumentIndex++];
	if ($strMatch == '%s' || $strMatch == '%m' || $strMatch == '%x') {
		if (get_magic_quotes_gpc()) {
			$strArgument = stripslashes($strArgument);
		}
	}
	if ($strArgument == 'NULL') {
		return 'NULL';
	}

	if (!$strArgument) {
		return '"'.$strArgument.'"';
	}
	switch ($strMatch) {
		case '%d': return (int)$strArgument;
		case '%f': return (float)$strArgument;
		case '%s': return '"'.mysql_real_escape_string($strArgument).'"';
		case '%m': return '"'.ubcode_add(mysql_real_escape_string($strArgument)).'"';
		case '%x': return '"'.comm_emo(mysql_real_escape_string($strArgument)).'"';
		case '%b': return (int)((bool)$strArgument);
	}
}

function SQL($strSql){
	global $arrArguments, $intArgumentIndex;
	$arrArgs = func_get_args();
	array_shift($arrArgs);
	$arrArguments = $arrArgs;
	$intArgumentIndex = 0;
	return preg_replace_callback('/(%[fdsbmx])/', 'parseArgument', $strSql);
}

function intoDB($a, $typ = ''){
	if ($a == 'NULL') return 'NULL';
	switch($typ) {
		case 'N': return SQL('%d', $a);
		case 'F': return SQL('%f', $a);
		default: return SQL('%s', $a);
	}
}

//default 0 for index page >> check file exists
function multiAssoc($array,$lvl=2){
	$r = array();
	if ($array) {
		foreach ($array as $k => $v) {
			$v0 = array_slice($v,$lvl);
			if (count($v0) == 1) {
				$v0 = reset($v0);
			}
			if ($lvl == 1) {
				$r[trim(reset($v))] = $v0;
			} else if ($lvl == 2) {
				$r[trim(reset($v))][trim(next($v))] = $v0;
			} else if ($lvl == 3) {
				$r[trim(reset($v))][trim(next($v))][trim(next($v))] = $v0;
			} else if ($lvl == 4) {
				$r[trim(reset($v))][trim(next($v))][trim(next($v))][trim(next($v))] = $v0;
			}
		}
	}
	return $r;
}

/**
 * cleanup before displaying information in browser
 *
 * @param mixed type
 * @return mixed type safe to display in browser
 */
function clean($a){
	if (is_array($a)) {
		foreach ($a as $k => $v) {
			if (is_array($v)) {
				$a[$k] = clean($v);
			} else {
				$a[$k] = intoBrowser($v);
			}
		}
	} else if ($a != '') {
		$a = intoBrowser($a);
	}
	return $a;
}

function cleanupJS($s){
	if (is_array($s)) {
		foreach ($s as $k => $v) {
			if (is_array($v)) {
				$s[$k] = cleanupJS($v);
			} else {
				$s[$k] = removeSpecialChar($v);
			}
		}
	} else if ($s != '') {
		$s = removeSpecialChar($s);
	}
	return $s;
}

function removeSpecialChar($s){
	$s = htmlspecialchars($s);
//	$s = str_replace('"','&quot;',$s);
	$s = str_replace("\\", '(', $s);
	$s = str_replace("/", ')', $s);
	$s = str_replace("'", '\\\'', $s);
	$s = preg_replace("/(\r\n|\n|\r)/", '{br}', $s);
	return $s;
}

function cleanForm($a, $type = 1){
	if (is_array($a)) {
		foreach ($a as $k => $v) {
			$a[$k] = cleanForm($v, $type);
		}
	} else if ($a) {
		$a = intoForm($a, $type);
	}
	return $a;
}

/**
 * safe to display in the form
 *
 * @param unknown_type $a
 * @param unknown_type $type
 * @return unknown
 */
function intoForm($a,$type=1){
	if (get_magic_quotes_gpc()) {
		$a = stripslashes($a);
	}
	if ($type == 1) {
		$a = htmlspecialchars($a);
		$a = str_replace("'", '&#39;', $a);
	}elseif ($type == 3) {//for WYMeditor
		$a = str_replace('&gt;', '<', $a);
		$a = str_replace('&lt;', '>', $a);
		$a = str_replace("\n", '<br/>', $a);
		$inf = explode("\r", $a);
		$a = '';
		foreach ($inf as $k => $line) {
			$a .= trim($line);
		}
		$a = addslashes($a);
	}
	return $a;
}

function intoBrowser($a, $type = 1){
	if (get_magic_quotes_gpc()) {
		$a = stripslashes($a);
	}
	if ($type == 1) {
		$a = htmlspecialchars($a);
	}
	return $a;
}

/**
 * set header for listing table , can set option
 * @param $txt
 * @return unknown_type
 */
function fw_head_list($txt){
	if (INF_HEADER_TXT == 'ucwords') {
		return ucwords(strtolower($txt));
	} else {
		return $txt;
	}
}

function fw_update_primary_page($opt, $basics){
	global $db;
	//remove from fav&
	if ($opt == 'update') {
		//FAV
		$sql = SQL('UPDATE gain_fw_fav SET info=%s WHERE item=%s AND item_id=%d', $basics['item_display'], $basics['entity'], $basics['id']);
		$db->Execute($sql);

		//RECENT PAGE
		$sql = SQL('UPDATE gain_fw_recent_page SET title=%s WHERE item=%s AND item_id=%d', $basics['item_display'], $basics['entity'], $basics['id']);
		$db->Execute($sql);
	} else if ($opt == 'delete') {
		//FAV
		$sql = SQL('DELETE FROM gain_fw_fav WHERE item=%s AND item_id=%d', $basics['entity'], $basics['id']);
		$db->Execute($sql);

		//RECENT PAGE
		$sql = SQL('DELETE FROM gain_fw_recent_page WHERE item=%s AND item_id=%d', $basics['entity'], $basics['id']);
		$db->Execute($sql);
	}
}

function fw_recent_page($title, $basics){
	global $db;
	//$link = basename(curPageURL(0));
	$link = gain_entity_get_entity_detail($basics['entity'], 'detail_link');
	if ($link) {
		$link .= $basics['id'];
		//remove recent page exist
		$sql = SQL('DELETE FROM '.PREFIX.'fw_recent_page
		WHERE id_user=%d
		AND item=%s
		AND item_id=%s', $_SESSION[SESSION_L], $basics['entity'], $basics['id']);
		$db->Execute($sql, 'fw');

		//add recent pages
		$search_token = md5(time().$_SESSION[SESSION_L]);
		$sql = SQL('INSERT INTO '.PREFIX.'fw_recent_page(search_token, id_user, item, item_id, title, link, search_time) VALUES(%s,%d,%s,%s,%s,%s,NOW())', $search_token, $_SESSION[SESSION_L], $basics['entity'], $basics['id'], $title, $link);
		$db->Execute($sql, 'fw');
	}
}

function fw_recent_page_lookup($mod){
	$detail_link = gain_entity_get_entity_detail($mod, 'detail_link');
	$recent = fw_recent_page_list(1);
	if ($recent[$mod]) {
		foreach ($recent[$mod] as $mod => $v) {
			$recent2[str_replace($detail_link, '', $v['link'])] = $v['title'];
		}
	}
	return $recent2;
}

function fw_recent_page_list($lookup=''){
	global $db, $cache_entity;

	$sql = SQL('SELECT title, link, item
	FROM '.PREFIX.'fw_recent_page
	WHERE id_user=%d
	ORDER BY search_time DESC
	LIMIT 0,200', $_SESSION[SESSION_L]);
	$rsl = $db->GetArray($sql, 'fw');
	$entites['all_record'] = 1;
	foreach ($rsl as $i) {
		$entites[$i['item']] = 1;
		$recent['all_record'] = $rsl;
		$recent[$i['item']][] = $i;
	}
	if ($lookup == 1) {
		return $recent;
	}

	ksort($entites);
	if ($recent) {
		foreach ($recent as $k => $v) {
			$cutted[$k] = array_slice($recent[$k], 0, 12);
		}
	}
	foreach ($cache_entity  as $k => $v) {
		$entity_info[$v['module']] = $v;
	}

	$r .= '<div style="padding: 5px 0 5px 0;">';
	foreach ($entites as $en => $v) {
		if ($en == 'all_record') {
			$r .= '<a id="recent_icon_'.$en.'" rel="'.$en.'" class="recent_icon active_recent_icon" style="cursor: pointer; border-right: 1px solid #DDD;"><img title="'.msg('recent_'.$en).'" src="files/note/entity/'.$en.'.png"/></a>';
		} else {
			$r .= '<a id="recent_icon_'.$en.'" rel="'.$en.'" class="recent_icon" style="cursor: pointer; border-right: 1px solid #DDD;"><img title="'.msg('recent_'.$en).'" src="files/note/entity/'.$entity_info[$en]['table_name'].'.'.$entity_info[$en]['icon'].'"/></a>';
		}
	}
	$r .= '</div><br class="clr"/>';
	if ($cutted) {
		$r .= '<div id="recent_page_item">';
		foreach ($cutted as $entity => $v) {
			$display = '';
			if ($entity != 'all_record') {
				$display = 'display: none;';
			}
			$r .= '<div id="recent_'.$entity.'" style="'.$display.' margin-top: 5px;"><ul>';
			foreach ($v as $k => $i) {
				$icon = '';
				if ($entity == 'all_record') {
					$icon = gain_entities_get_entity_icon($i['item']);
				}
				$r .= '<li><a href="'.$i['link'].'">'.$icon.' '.$i['title'].'</a></li>';
			}
			$r .= '</ul></div>';
		}
		$r .= '</div>
		<script type="text/javascript">
			$(document).ready( function() {
				$("a.recent_icon").each(function(){
					$(this).click( function() {
						var recent_p_item = $(this).attr("rel");
						$("a.recent_icon").removeClass("active_recent_icon");
						$(this).addClass("active_recent_icon");
						$("div#recent_page_item div").hide();
						$("div#recent_page_item div#recent_" + recent_p_item).show();
					});
				});
			});
		</script>';
	} else {
	    $r .= '<div>'.msg('no recent page').'</div>';
	}
	return $r;
}

function curPageURL($get_request = 1){
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {
		$pageURL .= "s";
	}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
		if ($get_request == 1) {
			$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
		} else {
			$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["SCRIPT_NAME"];
		}
	}
	return $pageURL;
}


/** prepare vars for replace */
function fw_format_item_get($item){
	preg_match_all('!\{(.*)\}!Usi', $item, $matches1);
	preg_match_all('!\^(.*)\^!Usi', $item, $matches2);
	preg_match_all('!\[(.*)\]!Usi', $item, $matches3);
	$matches['A'] = $matches1[1];
	$matches['B'] = $matches2[1];
	$matches['C'] = $matches3[1];
	return $matches;
}

/** replace found vars */
function fw_format_item_change($item, $matches, $row, $tabinfos){
	if ($matches['A']) {
		foreach ($matches['A'] as $ky => $vl) {
			$item = str_replace('{'.$vl.'}', $row[$vl], $item);
		}
	}
	if ($matches['B']) {
		foreach ($matches['B'] as $ky => $vl) {
			if (substr_count($vl, ';')>0) {
				$inf = explode(';', $vl);
			} else {
				$inf[0] = $vl;
				$inf[1] = 'Y-m-d';
			}
			//if date is timestamp then we need to change format
			if (strstr($row[$inf[0]], '-')) {
				$row[$inf[0]] = strtotime($row[$inf[0]]);
			}
			$item = str_replace('^'.$vl.'^', date($inf[1], $row[$inf[0]]), $item);
		}
	}
	if ($matches['C']) {
		foreach ($matches['C'] as $ky => $vl) {
			$inf2 = explode(';', $vl);
			$vk = $row[$inf2[1]];
			if ($vk != '' && $inf2[0]) {
				$str = $tabinfos[$inf2[0]][$vk];
				$item = str_replace('['.$vl.']', $str, $item);
			} else {
				$item = str_replace('['.$vl.']', '', $item);
			}
		}
	}
	return $item;
}

/**
 * get param field primary_field, zone[!now fw get zone number by reg], search[!now we dont use this param]
 * param can separate by ';' for get more than one param
 * fw_check_param_field($fields,'primary_field','label') return
 * @return array of key
 */
function fw_check_param_field($fields, $param, $act = ''){
	//clean values
	$clean_me = fw_data_cleanup($fields, $basics);
	$fields = $clean_me[0];

	$param_arr = explode(';', $param);
	if ($fields && $param_arr) {
		foreach ($fields as $ky => $vl) {
			foreach ($param_arr as $k => $pm) {
				if (array_key_exists($pm, $vl)) {
					if ($pm == 'zone') {
						$key[$pm][$vl['zone']] = 1;
					} else {
						if ($pm == 'search') {
							if ($vl['search'] != 0) {
								$key[$pm][] = $ky;
							}
						} else {
							$key[$pm][] = $ky;
						}
					}
				}
			}
		}
		if ($act == '') {
			return $key;
		}
	}
	if ($key) {
		if (strstr($act, strtolower('label')) && $key['primary_field']) {
			$r['label'] = fw_check_label($key['primary_field']);
		} else {
			$r['label'] = 'need key for "primary_field"';
		}

		//remove/comment this part
		if (strstr($act, strtolower('zone'))) {
			//TODO change fw to return this array.. and loop with this
			$r['zone'] = count($key['zone']);
		} else {
			$r['zone'] = 'need key for "zone"';
		}

		if (strstr($act, strtolower('search'))) {
			$r['search'] = fw_check_label($key['search']);
		}
		return $r;
	}
}

/**
 * @param array primary field
 *
 */
function fw_check_label($primary_field){
	if ($primary_field) {
		array_walk($primary_field, 'array_alter', 'field_');
		return implode(' ', $primary_field);
	}
}

/**
 * get name of item that was set by primary_field
 * @param $fields
 * @param $basics
 * @return unknown_type
 */
function fw_item_display($fields, &$basics){
	global $db;
	if ($_REQUEST['link'] != 'add' && $basics['id'] != '' && !isset($basics['show_tab'])) {
		//return key that was set for primary_field
		if (!$basics['item_display']) {
			$r = fw_check_param_field($fields, 'primary_field');
			if ($r) {
				$f['table'][$basics['table']] = 1;
				$f['where'][SQL($basics['table'].'.'.$basics['key'].'=%d', $basics['id'])] = 1;
				foreach ($r['primary_field'] as $k => $v) {
					if ($fields[$v]['lookup']) {
						if (is_array($fields[$v]['lookup']['display'])) {
							$ds = 'CONCAT(';
							foreach ($fields[$v]['lookup']['display'] as $k2 => $v2) {
								if ($k2 > 0) {
									$ds .= '," ",';
								}
								$ds .= $fields[$v]['lookup']['table'].'.'.$v2.',""';
							}
							$ds .= ') AS '.$v;
							$f['select'][$ds] = 1;
						} else {
							$f['select'][$fields[$v]['lookup']['table'].'.'.$fields[$v]['lookup']['display']] = 1;
						}
						$f['table'][$fields[$v]['lookup']['table']] = 1;
						$f['where'][$fields[$v]['lookup']['table'].'.'.$v.'='.$basics['table'].'.'.$v] = 1;
					} else {
						if ($fields[$v]['type'] == 'name') {
							$f['select'][$basics['table'].'.'.$v.'_display'] = 1;
						} else {
							$f['select'][$basics['table'].'.'.$v] = 1;
						}
					}
				}
				if ($f['select']) {
					$sql = 'SELECT '.implode(', ', array_keys($f['select']));
					$sql .= ' FROM '.implode(', ', array_keys($f['table']));
					$sql .= ' WHERE '.implode(' AND ', array_keys($f['where']));
				}
				$rsl = $db->GetRow($sql, 'fw');
				if ($rsl) {
					foreach ($rsl as $k => $v) {
						if ($fields[$k]['primary_field_pattern'] && $v != '') {
							$rsl[$k] = str_replace('{items}', $v, $fields[$k]['primary_field_pattern']);
						} else if ($fields[$k]['type'] == 'select') {
							$rsl[$k] = $fields[$k]['values'][$v];
						}
					}

					$basics['item_display'] = implode(' ', $rsl);

					return $basics['item_display'];
				} else {
					return;
				}
			}
		} else {
			return $basics['item_display'];
		}
	}
}

function fw_set_page_title($fields, &$basics, $main_title){
	global $tpl, $cm_menu;
	$title = fw_item_display($fields, $basics);
	if ($title != '') {
		if ($basics['recent_page'] == 1) {
			fw_recent_page($title, $basics);
		}
		$title_header = $title;
	} else {
		if ($cm_menu['M'][$basics['entity']]['M']) {
			$title_header = $cm_menu['M'][$cm_menu['M'][$basics['entity']]['M']]['H'];
		} else {
			$title_header = $main_title;
		}
	}
	$title_header = $title_header;
	$tpl->set('tpl_title', $title_header);
}

/**
 *
 * Enter description here ...
 * @param $table
 * @param $redo
 */
function fw_cache($table, $redo = 0){
	global $db;
	$exists = 0;
	$file = PATH.'files/cache/'.$table.'.php';
	$cn = strlen(PREFIX);
	if (!file_exists($file)) {
		$not_exists = 1;
	}
	$skip_columns = array('added', 'added_by', 'updated', 'updated_by', 'removed', 'removed_by');
	if ($redo == 1 || $not_exists == 1) {
		$custom_cache = 'cache_'.$table;
		if (function_exists($custom_cache)) {
			$custom_cache();
		} else {
			//see if we can fetch extra info
			//$custom_cache = 'cache_'.$table;
			//set ORDER BY base on "default_sort" setting
			$order_by = '';
			//TODO del require_once('modules/settings.php');
			$entity = str_replace(PREFIX, '', $table);
			$function = 'gain_settings_'.$entity;
			if (function_exists($function)){
				$setting_info = $function('', 1);
				if (is_array($setting_info)) {
					if (!empty($setting_info[$entity]['table']['default_sort']['by'])) {
						$order_by = $setting_info[$entity]['table']['default_sort']['by'];
						//if (strstr($order_by,'.')) $order_by = substr($order_by,strpos($order_by, '.')+1);
						if (strstr($order_by, '.')) {
							$order_by = str_replace($table.'.', '', $order_by);
						}
						if (empty($setting_info[$entity]['table']['default_sort']['order'])) {
							$sort_by = 'ASC';
						} else {
							$sort_by = $setting_info[$entity]['table']['default_sort']['order'];
						}
						$order_by = ' ORDER BY '.$order_by.' '.$sort_by;
					}
				}
			}
			$sql = 'SELECT * FROM '.$table;
			if ($order_by != '') {
				$sql .= $order_by;
			}

			$cache = fw_clean_cache($db->GetAssoc($sql, 'fw'));
			//reorder cache if we have column order_list
			$check = array_slice($cache, 0, 1);

			if ($check[0]) {
				if (array_key_exists('order_list', $check[0])) {
					sort_array_2d($cache, 'order_list');
				} else {
					$field_name = str_replace(PREFIX,'', $table).'_name';
					if (array_key_exists($field_name, $check[0])) {
						sort_array_2d($cache, $field_name);
					} else if ($order_by == '') {
						$sql = 'SHOW FULL FIELDS FROM '.$table;
						$full_fields = $db->GetArray($sql);
						sort_array_2d($cache, $full_fields[1]['Field']);
					}
				}
			}
			$c1 = '<?php
$cache_'.substr($table,$cn).'_remove = array(
';
			$c2 = '
$cache_'.substr($table,$cn).' = array(
';
			if (count($cache)>0) {
				foreach ($cache as $k => $v) {
					if ($k>0) {

						if ($v['removed'] == '') {
							$c2 .= $k.' => array(';
						} else {
							$c1 .= $k.' => array(';
						}
						foreach ($v as $m => $n) {
							if (!in_array($m,$skip_columns)) {
								if ($v['removed'] == '') {
									$c2 .= '\''.$m.'\' => \''.$n.'\',';
								} else {
									$c1 .= '\''.$m.'\' => \''.$n.'\',';
								}
							}
						}

						if ($v['removed'] == '') {
							$c2 .= '),'."\r\n";
						} else {
							$c1 .= '),'."\r\n";
						}
					}
				}
				$c1 = substr($c1, 0, -1);
				$c2 = substr($c2, 0, -1);
			}
			$c1 .= '
);
';
			$c2 .= '
);

$cache_'.substr($table, $cn).'_all = $cache_'.substr($table, $cn).'_remove + $cache_'.substr($table, $cn).';
?>';
			//write file
			file_put_contents($file, $c1.$c2);
		}
	}
	return $file;
}

function fw_clean_cache($a){
	if (is_array($a)) {
		foreach ($a as $k => $v) {
			if (is_array($v)) {
				$a[$k] = fw_clean_cache($v);
			} else if ($v != '') {
				$v = htmlspecialchars($v);
				$a[$k] = addslashes($v);
			}
		}
	} else if ($a != '') {
		$a = htmlspecialchars($a);
		$a = addslashes($a);
	}
	return $a;
}

function translate_date($format, $type = 'js_php'){
	// javascript to php format
	$date_format = array(
		'dd' => 'd',
		'd' => 'j',
		'DD' => 'l',
		'D' => 'D',
		'o' => 'z',
		'mm' => 'm',
		'm' => 'n',
		'MM' => 'F',
		'M' => 'M',
		'yy' => 'Y',
		'y' => 'y'
	);
	
	if ($type == 'php_js') {
		//flip array so can be translated from PHP into JS
		$date_format = array_flip($date_format);
	} else if ($type == 'php_java') {
		$date_format = array(
			'd'=>'dd',
			'j'=>'d',
			'l' => 'EEEEE',
			'D' => 'EEE',
			'm' => 'MM',
			'n' =>'M',
			'F' => 'MMMMM',
			'M' => 'MMM',
			'Y' => 'yyyy',
			'y' => 'yy'
		);
	}

	//string translation function
	return strtr($format,$date_format);
}

/**
 * array('a' => array('a' => 1,'b' => 2))
 * gain_return_me($arr,'a')
 * @param $arr
 * @param $sort
 * @return unknown_type
 */
function fw_sort_array($arr, $sort){
	if ($arr) {
		foreach ($arr as $k => $v) {
			$sort_item[$v[$sort]][$k] = $v;
		}
		ksort($sort_item);
		foreach ($sort_item as $k => $v) {
			foreach ($v as $k2 => $v2) {
				$sort_itemx[$k2] = $v2;
			}
		}
		return $sort_itemx;
	}
}

/**
 * fetch version of application and return it in URL friendly form
 * @return string with version number
 */
function gain_version(){
	global $global_config;
	return str_replace('.', '0', $global_config['system']['version_core']);
}

/**
 *
 * @param $icon_part
 * @param $title
 * @return unknown_type
 */
function fw_show_title($t_name, $icon_part){
	//$id = 'fw_show_title_'.$t_name;
	//$icon = '<img src="'.$icon_part.'" onmouseout="$(\'#'.$id.'\').hide();" onmouseover="fw_show_popup_title(\''.$id.'\', this);"/>';
	$title_div = '<div id="'.$t_name.'" class="hide corner" style="border: 1px solid #e9d315; padding: 4px; background: #f9f2ba none repeat scroll 0% 0%; position: absolute; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; z-index: 3; font-size: 11px; text-shadow:0 0 1px white;"></div>';
	return $icon_part.$title_div;
	//return array('icon' => $icon, 'div' => $title_div);
}

/**
 * return aging
 * beem created: didnot test it yet!
 */
function fw_set_aging($aging = '', $color = ''){
	global $global_config;
	if ($global_config['system']['aging_colors']) {
		$c = array_keys($global_config['system']['aging_colors']);
		$cl = array_values($global_config['system']['aging_colors']);
		$cnt = count($global_config['system']['aging_colors']);

		$p = (int)15/$cnt;

		if ($aging == '') {
			for ($i=0; $i<$cnt; $i++) {
				if ($i == ($cnt-1)) {//last
					$aging_list[$i] = $c[($i-1)].' days ++';
					$colors[$aging_list[$i]] = 'CC0000';
				} else if ($i == 0) {//first
					$aging_list[$i] = 'current';
					$colors[$aging_list[$i]] = $cl[$i];
				} else {
					$aging_list[$i] = $c[($i-1)].' days';
					$colors[$aging_list[$i]] = $cl[($i)];
				}
			}
			if ($color == 1) {
				return array('order' => $aging_list, 'color' => $colors);
			}
			return $aging_list;
		} else {
			$aging_list = fw_set_aging();
			$age = '';
			for ($i=$cnt; $i>=0; $i--) {
				if ($age == '') {
					if ($i == $cnt) {//last4
						if ($aging > $c[($i-1)]) {
							$age = $aging_list[$i];
						}
					} else if ($i != 0) {
						if ($aging > $c[$i-1]) {
							$age = $aging_list[$i];
						}
					} else {//first0
						$age = 'current';
					}
				} else {
					$i = -1;
				}
			}
			return $age;
		}
	}

	return $aging;
}

function gain_log($msg, $file = 'log.txt') {
	$h = fopen(PATH.'files/temp/'.$file, 'a+');
	fwrite($h, date('Y-m-d H:i:s')."\t".$msg."\r\n");
	fclose($h);
}

/**
 * for keep cron information
 * Enter description here ...
 * @param $type
 * @param $extra
 * @param $return
 */
function gain_fw_cron($type, $extra = '', $return = ''){
	global $db;
	if ($return == '') {
		$now = date('Y-m-d H:i:s');
		$sql = SQL('INSERT INTO gain_fw_cron(cron_date, cron_type, extra) VALUES(%s, %s, %s)', $now, $type, $extra);
		$db->Execute($sql);
	} else {
		//get last update
		$sql = SQL('SELECT cron_date
		FROM gain_fw_cron
		WHERE cron_type=%s', $type);
		if ($extra != '') {
			$sql .= SQL(' AND extra=%s', $extra);
		}
		$sql .= ' ORDER BY cron_date DESC';
		return strtotime($db->GetOne($sql));
	}
}

function gain_minify($content) {
	//max number of compressed files at once
	$limit = 10;
	$minify_file = '';
	$file_types_reg = array(
		'css' => array(
			'regex' => '@\<link rel\=\"stylesheet\" type=\"text\/css\" href\=\"(.*)\?min" />@iU',
			'pattern' => '<link rel="stylesheet" href="[[minify]]" type="text/css" />'
		),
		'js' => array(
			'regex' => '@\<script type\=\"text\/javascript\" src\=\"(.*)\?min"><\/script>@iU',
			'pattern' => '<script type="text/javascript" src="[[minify]]"></script>'
		)
	);
	foreach($file_types_reg as $k => $v) {
		preg_match_all($v['regex'], $content, $match);
		$compress_files = array();
		$c = 0;
		foreach ($match[1] as $m => $n) {
			++$c;
			if ($c%$limit == 0) {
				++$i;
			}
			$compress_files[$i][] = $n;
			$match[0][$m] .= "\r\n";
		}
		if ($compress_files) {
			if (TOOL_COMPRESS_JSCSS == 1) {//compress files
				foreach ($compress_files as $files) {
					$files = implode(',', $files);
					$content = str_replace($match[0], '', $content);
					$minify_file .= str_replace('[[minify]]', 'min/?f='.$files.'&v='.gain_version(), $v['pattern'])."\r\n";
				}
			} else {//add version only
				foreach ($match[1] as $e) {
					$content = str_replace($e.'?min', $e.'?v='.gain_version(), $content)."\r\n";
				}
			}
		}
	}
	$content = str_replace('<!-- merge content -->', $minify_file, $content);
	return $content;
}

function get_age ($start, $end = '') {
	if ($start && $start != "0000-00-00" && $start != "0000-00-00 00:00:00") {
		if (!$end) {
			$end = date('Y-m-d');
		}
		$str_start = strtotime($start);
		$str_end = strtotime($end);

		$age = date('Y', $str_end) - date('Y', $str_start);

		if (date('m-d', $str_start) > date('m-d', $str_end)) {
			$age -= 1;
		}
	}
	return (int)$age;
}
?>